<template>
  <view class="PAGE">
    <view class="content">
      <view class="avatar">
        <button class="avatar-wrapper-button" open-type="chooseAvatar" @chooseavatar="getUseInfo">
          <image v-if="avatar" :src="avatar" class="avatar" style="margin-top: 7px"></image>
          <TnAvatar v-else icon="my-job-fill" size="xl"></TnAvatar>
        </button>
      </view>
      <view class="cu-form-group-box margin-top">
        <view class="title">
          <text style="color: red">*</text>商户名</view>
        <m-input ref="account" v-model="inputData1.account" title="微信号"
                 placeholder="请输入商户名"></m-input>
      </view>
      <view class="line"></view>
      <view class="cu-form-group-box">
        <view class="title">性别</view>
        <view @click="showPop('sex')">
          <text class="pl-change" v-if="sex === ''">请选择</text>
          <text v-else class="pl-change">{{ (Number(sex)) === 1 ? '男' : '女' }}</text>
          <TnIcon name="right" />
        </view>
      </view>
      <view class="line"></view>
      <view class="cu-form-group-box">
        <view class="title"> <text style="color: red">*</text>手机号码</view>
        <m-input ref="mobile" v-model="inputData1.mobile" type="number" title="微信号"
                 placeholder="请输入手机号码"></m-input>
      </view>
      <view class="err-msg"></view>
      <view class="line"></view>
      <view class="cu-form-group-box">
        <view class="title">微信号</view>
        <m-input ref="wxCode" v-model="inputData1.wxCode" title="微信号"
                 placeholder="请输入微信号"></m-input>
      </view>
      <view class="line"></view>
      <view class="cu-form-group-box">
        <view class="title">接单经验</view>
        <view @click="openPicker = true">
          <text class="pl-change">{{inputData1?.acceptanceExperience ? inputData1?.acceptanceExperience : "请选择"}}</text>
          <TnIcon name="right" />
        </view>
<!--        <m-input ref="wxCode" v-model="inputData1.acceptanceExperience" title="接单经验"-->
<!--                 placeholder="请输入接单经验"></m-input>-->
      </view>
      <view class="line"></view>
      <view class="cu-form-group-box" @click="showPopup = true">
        <view class="title">接单类目</view>
        <view class="">
          <text class="pl-change" v-if="orderCategoryOne.length === 0 || (orderCategoryOne.length > 0 && orderCategoryOne[0] === '')">请选择</text>
          <text class="pl-change" v-else>{{getCategoryText()}}</text>
          <TnIcon name="right" />
        </view>
      </view>
      <view class="line"></view>
      <view class="cu-form-group-box">
        <view class="title">技能标签</view>
        <view class="" @click="showPopupV2 = true">
          <text class="pl-change" v-if="currentTagList.length === 0">请选择</text>
          <text class="pl-change" v-else>{{getTagText()}}</text>
          <TnIcon name="right" />
        </view>
      </view>
      <view class="line"></view>
      <view class="cu-form-group-box">
        <view class="title">商户类型</view>
        <view class="" @click="showPop('merchant')">
          <text class="pl-change" v-if="!merchantType">请选择</text>
          <text class="pl-change" v-else>{{getMerchantTypeText()}}</text>
          <TnIcon name="right" />
        </view>
      </view>
      <view class="line"></view>
      <view class="cu-form-group-box">
        <view class="title">个人简介
        </view>
      </view>
      <view class="cu-form-group-box">
        <textarea :maxlength="500" placeholder="请输入个人简介" v-model="inputData1.personalProfile" class="desc-text"></textarea>
      </view>
    </view>
    <view>
      <view class="btn" @click="submit" v-if="status === '' || status == '2'">保 存</view>
      <view class="btn" :disabled="true" v-else-if="status">{{ statusMap[status] }}</view>
      <view style="margin-bottom: 20px; display: flex; align-items: center; justify-content: center" v-if="isNew">
        <TnCheckbox active-color="#339af0" v-model="agent">我已阅读并同意</TnCheckbox>
        <text style="color: #339af0;" @click="toPage(1)">《用户服务协议》</text>
        <text style="color: #339af0" @click="toPage(2)">《隐私政策》</text>
      </view>
    </view>
<!--    -->
    <view>
      <TnPopup v-model="showPopup" bg-color="transparent" radius="0" open-direction="bottom" :safe-area-inset-bottom="false">
        <view class="type-box">
          <view class="title">请选择你接单的类型</view>
          <view class="item-content">
            <view class="item-box" :class="{'active': orderCategoryOne?.includes(item.categoryCode as string)}" v-for="(item, index) in categoryList" :key="index" @click="changeCategory(item)">
              {{item.categoryName}}
            </view>
          </view>
          <view class="footer">
            <view class="footer-left" @click="orderCategoryOne = []">重置</view>
            <view class="footer-right" @click="showPopup = false">确定</view>
          </view>
        </view>
      </TnPopup>
      <TnPopup v-model="showPopupV2" bg-color="transparent" radius="0" open-direction="bottom" :safe-area-inset-bottom="false">
        <view class="type-box">
          <view class="title">请选择你技能</view>
          <view class="item-content">
            <view class="item-box" :class="{'active': currentTagList?.includes(item.dictValue)}" v-for="(item, index) in sellTagList" :key="index" @click="changeTag(item)">
              {{item.dictValue}}
            </view>
          </view>
          <view class="footer">
            <view class="footer-left" @click="currentTagList = []">重置</view>
            <view class="footer-right" @click="showPopupV2 = false">确定</view>
          </view>
        </view>
      </TnPopup>
    </view>
    <view>
      <TnPopup v-model="showPopupSex" bg-color="transparent" radius="0" open-direction="bottom" :safe-area-inset-bottom="false">
        <view class="type-box type-box-sex">

          <view class="item-content-sex">
            <view class="item-box title-sex">{{popTitle}}</view>
            <view class="item-box" v-for="(item, index) in popList" :key="index" @click="selSex(item)">
              {{item.label}}
            </view>
            <view class="item-box mt18px" @click="showPopupSex = false">取消</view>
          </view>
        </view>
      </TnPopup>
      <TnPrivacyPopupBox agree-text="已阅读并同意" @open-protocol="protocolClickHandle" :agree-bg-color="'tn-blue'" privacy-contract-text="《平台规则》" @disagree="showPrivacyPopup = false" v-model="showPrivacyPopup" @agree-privacy-authorization="startAgree" />
    </view>

    <view>
      <TnPicker
          v-model="inputData1.acceptanceExperience"
          v-model:open="openPicker"
          :data="pickerData"
      />
    </view>

  </view>
</template>

<script lang="ts" setup>
import {ref, reactive} from 'vue'
import mInput from './components/m-input.vue';
import TnAvatar from '@tuniao/tnui-vue3-uniapp/components/avatar/src/avatar.vue'
import TnPopup from '@tuniao/tnui-vue3-uniapp/components/popup/src/popup.vue'
import TnIcon from '@tuniao/tnui-vue3-uniapp/components/icon/src/icon.vue'
import { uploadAvatar } from "@/api/upload";
import {addUserInfo, getFirstCategoryApi, getFirstSkillTagApi, queryUserInfo} from "@/api/login";
import { onLoad } from "@dcloudio/uni-app";
import { isPhone } from "@/utils/common";
import TnPicker from '@tuniao/tnui-vue3-uniapp/components/picker/src/picker.vue'
import TnPrivacyPopupBox from 'tnuiv3p-tn-privacy-popup-box/index.vue'
import TnCheckbox from '@tuniao/tnui-vue3-uniapp/components/checkbox/src/checkbox.vue'
import TnCheckboxGroup from '@tuniao/tnui-vue3-uniapp/components/checkbox/src/checkbox-group.vue'

const showPopup = ref(false);
const showPopupSex = ref(false);
const showPrivacyPopup = ref(false);
const showPopupV2 = ref(false); // 技能标签
const avatar = ref("");
const statusMap: any = {
  0: '待审核',
  1: '审核中',
  2: '审核通过',
  3: '审核不通过',
}
const status = ref("");

const protocolClickHandle = (e: any) => {
  uni.navigateTo({
    url: "/pages/user/platformRules/index",
  })
  return false;
}


// 响应式数据
const inputData1 = reactive({
  account: '',
  mobile: '',
  wxCode: "",
  personalProfile: "",
  acceptanceExperience: "",
})
const openPicker = ref(false);
const pickerData = ['1-2年', '3-5年', '6-10年', '10年以上'];
const orderCategoryOne = ref<string[]>([]); // 接单类目
const sellTagList = ref<any[]>([]);
const currentTagList = ref<string[]>([]);
// 组件引用
const account = ref<any>(null);
const mobile = ref<any>(null);
const popTitle = ref("");
const popList = ref<Array<any>>([]);

const agent = ref(false);
const toPage = (type: number) => {
  if (type === 1) {
    uni.navigateTo({
      url: "/pages/user/platformRules/index",
    })
  } else if (type === 2) {
    uni.navigateTo({
      url: "/pages/user/platformRulesV2/index",
    })
  }
}

const popMap: Record<string, any> = {
  sex: {
    title: "请选择你的性别",
    list: [
      {
        label: "男",
        value: 1
      },
      {
        label: "女",
        value: 0
      }
    ]
  },
  merchant: {
    title: "请选择你的商户类型",
    list: [
      {
        label: "个人",
        value: "10061001",
      },
      {
        label: "团体/工作室",
        value: "10061002"
      },
      {
        label: "企业",
        value: "10061003"
      }
    ]
  }
}

/**
 * 选择类目
 * @param item
 */
const changeCategory = (itemData: any) => {
  console.log(itemData, "--")
  const code = itemData.categoryCode;
  const findIndex = orderCategoryOne.value.findIndex((item: any) => {
    return item === code;
  })
  console.log(itemData, findIndex)
  if(findIndex === -1) {
    if(code) {
      orderCategoryOne.value.push(code);
    }

  } else {
    orderCategoryOne.value.splice(findIndex, 1);
  }
}

const changeTag = (itemData: any) => {
  const dictValue = itemData.dictValue;
  const findIndex = currentTagList.value.findIndex((item: any) => {
    return item === dictValue;
  })
  if(findIndex === -1) {
    currentTagList.value.push(dictValue);
  } else {
    currentTagList.value.splice(findIndex, 1);
  }
}

const getTag = async () => {
  const res: any = await getFirstSkillTagApi();
  if (res.code == 200) {
    sellTagList.value = res?.rows || [];
  }
}

const showPop = (type: string) => {
  popTitle.value = popMap?.[type]?.title || "";
  popList.value = popMap?.[type]?.list || [];
  showPopupSex.value = true;
}

const sex = ref("");
const selSex = (item: any) => {
  if(popList.value.length === 2) {
    sex.value = item.value;
  } else {
    merchantType.value = item.value;
  }

  showPopupSex.value = false;
}

const merchantType = ref(""); // 商户类型
const getMerchantTypeText = () =>{
  const list = popMap?.merchant?.list;
  const findIndex = list.findIndex((item: any) => {
    return item.value === merchantType.value
  })
  return popMap?.merchant?.list?.[findIndex]?.label || "";
}

const submit = async () => {
  // const startAgree
  if (isNew.value === true && agent.value === false) {
    uni.showToast({
      icon: 'none',
      title: "请先阅读并同意用户服务协议和隐私政策"
    })
    return;
  }
  if (!inputData1.account) return account.value.errorText('请正确填写商户名');
  if (!isPhone(inputData1.mobile)) return mobile.value.errorText('请正确填写手机号');
  if(avatar.value === "") {
    uni.showToast({
      icon: 'none',
      title: "请上传头像"
    })
    return;
  }
   const data = await uni.getStorageSync("userInfo");
    console.log(data)
    if(data?.nickname) {
      saveData()
    } else {
      showPrivacyPopup.value = true;
    }
}
const saveData = async () => {
  const params = {
    nickname: inputData1.account,
    phoneNumber: inputData1.mobile,
    wechatId: inputData1.wxCode,
    headSculpture: avatar.value, // 头像
    orderCategoryOne: orderCategoryOne.value.join(","), // 接单类型
    orderCategoryTwo: "", // 服务内容
    personalProfile: inputData1.personalProfile, // 个人简介
    acceptanceExperience: inputData1.acceptanceExperience, // 接单经验
    sex: sex.value,
    merchantType: merchantType.value,
    skillTags: currentTagList.value.join(","),
  }
  const res = await addUserInfo(params);
  if (res.code === 200) {
    const res = await queryUserInfo();
    if (res.code === 200) {
      uni.setStorageSync("userInfo", res.data)
    }
    await uni.navigateBack({delta: 1})

  } else {
    await uni.showToast({
      icon: 'none',
      title: res?.msg || ""
    })
  }
}

const startAgree = () =>{
  saveData();
  showPrivacyPopup.value = false;
}

const getUseInfo = async (data: any) => {
  avatar.value = data.detail.avatarUrl;
  try {
    const avatarRes = await uploadAvatar(avatar.value, 'avatar')
    if (avatarRes.code === 200) {
      avatar.value = avatarRes.data.url
    }
  } catch (e) {
    console.log(e)
  }
};

const categoryList = ref<Array<any>>([]);
const getCategory = async () => {
  const res = await getFirstCategoryApi();
  if (res.code === 200) {
    categoryList.value = res?.data || [];
  }
}

const getCategoryText = () => {
  let textList: any = [];
  for (let i = 0; i < orderCategoryOne.value.length; i++) {
    const findIndex = categoryList.value.findIndex((item: any) => {
      return item.categoryCode === orderCategoryOne.value[i]
    })
    if (findIndex > -1) {
      textList.push(categoryList.value[findIndex].categoryName);
    }
  }
  if (textList.length > 2) {
    return textList[0] + "、" + textList[1] + "...";
  } else {
    return textList.join("、");
  }
}

const getTagText = () => {
  let textList: any = [];
  for (let i = 0; i < currentTagList.value.length; i++) {
    const findIndex = sellTagList.value.findIndex((item: any) => {
      return item.dictValue === currentTagList.value[i]
    })
    if (findIndex > -1) {
      textList.push(sellTagList.value[findIndex].dictValue);
    }
  }
  if (textList.length > 2) {
    return textList[0] + "、" + textList[1] + "...";
  } else {
    return textList.join("、");
  }
}

const isNew = ref(true);
onLoad(async (query = { type: "" }) => {
  // 页面加载时执行的代码
  getCategory();
  getTag()
  if(query?.type === "update") {

    const userInfo = await uni.getStorageSync("userInfo");
    if(userInfo) {
      isNew.value = false;
    }
    inputData1.account = userInfo?.nickname || "";
    inputData1.mobile = userInfo?.phoneNumber || "";
    inputData1.wxCode = userInfo?.wechatId || "";
    avatar.value = userInfo?.headSculpture || "";
    inputData1.personalProfile = userInfo?.personalProfile || "";
    inputData1.acceptanceExperience = userInfo?.acceptanceExperience || "";

    const list = userInfo.orderCategoryOne.split(",");
    if(list[0]) {
      orderCategoryOne.value = list;
    }
    merchantType.value = userInfo?.merchantType || "";
    sex.value = userInfo.sex;
    currentTagList.value = userInfo?.skillTagsList || [];
    status.value = userInfo?.reviewStatus || "";
  }
})
</script>


<style scoped lang="scss">
.PAGE {
  padding: 25rpx;
  border-radius: 20rpx;
  .avatar-wrapper-button {
    margin-top: -27px;
    height: 120px ;
    padding-top: 40px;

  }
  .content {
    border-radius: 20rpx;
    background: #ffffff;
    padding: 80rpx 10rpx;
    margin-top: 100rpx;
    .avatar {
      position: absolute;
      width: 180rpx;
      height: 180rpx;
      border-radius: 50%;
      left: calc(50% - 90rpx);
      top: 40rpx;
      overflow: hidden;
    }
    .line {
      height: 1px;
      width: 100%;
      background: #f2f2f2;
    }
    .title {
      color: #666666;
    }
  }
}
.cu-form-group-box {
  input {
    text-align: right;
  }
}

.type-box {
  min-height: 250rpx;
  width: 100%;
  background: #fff;
  padding: 20rpx;
  border-radius: 20rpx 20rpx 0 0;
  .title {
    width: 100%;
    text-align: center;
    color: #999999;
    font-size: 32rpx;
  }
  .item-content {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    .item-box {
      width: 220rpx;
      height: 80rpx;
      color: #4e5969;
      font-size: 28rpx;
      background: #f7f8fa;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 20rpx ;
    }
    .active {
      color: #165Dff;
      background: #e8f3ff;
    }
  }
  .footer {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;
    margin-top: 20rpx;
    .footer-left {
      flex: 1;
      height: 80rpx;
      background: #e8f3ff;
      margin-right: 10rpx;
      text-align: center;
      line-height: 80rpx;
      color: #165Dff;
    }
    .footer-right {
      flex: 1;
      height: 80rpx;
      margin-left: 10rpx;
      background: #165Dff;
      color: #ffffff;
      text-align: center;
      line-height: 80rpx;
    }
  }
  .item-content-sex {
    .title-sex {
      color: #999999;
    }
    .item-box {
      height: 160rpx;
      text-align: center;
      line-height: 160rpx;
      /* 外部/白色 */
      background: #FFFFFF;
      box-shadow: inset 0px -0.5px 0px 0px #E5E6EB;
    }
  }
}
.type-box-sex {
  background: #F2F3F5;
  padding: 0;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  overflow: hidden;
}
.cu-form-group-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #ffffff;
  min-height: 100rpx;
  padding: 1rpx 30rpx;
  .desc-text {
    background: #fafafa;
    padding: 20rpx;
    border-radius: 20rpx;
    width: 100%;
  }
}
.btn {
  width: calc(100% - 40rpx);
  height: 80rpx;
  margin: 20rpx;
  background: #4B7BF5;
  border-radius: 40rpx;
  text-align: center;
  line-height: 80rpx;
  color: #ffffff;
  font-size: 28rpx;
}
.pl-change {
  color: #666666;
}
.err-msg {
  width: 100%;
  text-align: right;
  padding-right: 25rpx;
  color: #ff0000;
}
.mt18px {
  margin-top: 36rpx;
}
</style>